from flask import Blueprint, render_template, flash, redirect, request,g
from models import File, User
from flask_wtf import FlaskForm
from wtforms import FileField
from database import create_app

file = Blueprint("file", __name__, url_prefix="/file")

# 自定义文件上传的表单类
class FileForm(FlaskForm):
    from flask_wtf.file import FileRequired
    file = FileField("file", validators=[FileRequired()])

@file.route("/")
# @login_required
def get__file():
    user= g.user
    files = File.query.filter(File.user_id == user.user_id).all()
    return render_template("index.html", username=user.username, files=files)


@file.route("/upload")
# @login_required
def get__upload():
    return render_template("file_upload.html", form=FileForm())


@file.route("/upload", methods=["POST"])
# @login_required
def post__upload():
    user= g.user

    try:
        form = FileForm()
        assert form.validate_on_submit(), "invalid form fields"

        data = form.file.data
        # 获取文件名
        filename = data.filename

        # 实现文件的快传功能，某一用户的文件若存在，则不重复上传
        # 判断该用户是否存有此文件,没有找到，返回none
        existing_file = File.query.filter_by(
            file_name=filename, user_id=user.user_id
        ).first()

        if existing_file is None:
            File.upload_file(user, data)
            flash("上传成功！")
        else:
            flash("文件已存在！")

    except AssertionError as e:
        message = e.args[0] if len(e.args) else str(e)
        flash("上传失败！" + message)
    return redirect("/file")


@file.route("/download")
# @login_required
def get__download():
    user= g.user
    try:
        filename = request.args.get("filename")
        assert filename, "missing filename"
        type = request.args.get("type")

        assert type, "missing type"
        assert type in (
            "encrypted",
            "plaintext",
            "signature",
            "hashvalue",
        ), "unknown type"
        return File.download_file(user, filename, type)
    except AssertionError as e:
        message = e.args[0] if len(e.args) else str(e)
        flash("下载失败！" + message)
        return redirect("/file")
